﻿// Example based on MSDN http://msdn.microsoft.com/en-us/library/ms731758.aspx

namespace EyeOpen.WcfSelfHosting.Shell
{
	using System;
	using System.ServiceModel;
	using System.ServiceModel.Description;

	internal class Program
	{
		public static void Main()
		{
			var baseAddress = new Uri("http://localhost:9000/hello");

			// Create the ServiceHost
			using (var host = new ServiceHost(typeof(HelloWorldService), baseAddress))
			{
				// Enable metadata publishing
				var serviceMetadataBehavior =
					new ServiceMetadataBehavior
						{
							HttpGetEnabled = true,
							MetadataExporter = { PolicyVersion = PolicyVersion.Policy15 }
						};
				host.Description.Behaviors.Add(serviceMetadataBehavior);

				// Retrieve the ServiceDebugBehavior to include exception
				// details raised from the service
				var serviceDebugBehavior = (ServiceDebugBehavior)host.Description.Behaviors[typeof(ServiceDebugBehavior)];
				serviceDebugBehavior.IncludeExceptionDetailInFaults = true;

				// Open the ServiceHost to start listening for messages. Since
				// no endpoints are explicitly configured, the runtime will create
				// one endpoint per base address for each service contract implemented
				// by the service.
				try
				{
					host.Open();
				}
				catch (AddressAccessDeniedException exception)
				{
					ShowHowToFixAndRethrow(exception);
				}

				Console.WriteLine("The service is ready at {0}", baseAddress);

				var client = new HelloWorldClient(new BasicHttpBinding(), new EndpointAddress(baseAddress));
				var proxy = client.ChannelFactory.CreateChannel(new EndpointAddress(baseAddress));

				Console.WriteLine(proxy.SayHello("Bill"));
				client.Close();
			}

			Console.ReadLine();
		}

		private static void ShowHowToFixAndRethrow(AddressAccessDeniedException innerException)
		{
			const string HelpLink = "http://stackoverflow.com/questions/885744/wcf-servicehost-access-rights";

			var message =
				"See here how to solve the exception {0}{1}" +
				string.Empty + "{0}{0}" +
				"Launch the command:{0}" +
				"netsh http add urlacl url=http://+:9000/hello user=mylocaluser";

			message =
				message.FormatEx(Environment.NewLine, HelpLink);

			var exception =
				new AddressAccessDeniedException(message, innerException)
					{
						HelpLink = HelpLink
					};

			throw exception;
		}
	}
}